package org.example.ssh

import net.schmizz.sshj.SSHClient
import net.schmizz.sshj.sftp.SFTPClient
import org.example.ssh.base.deleteDirectoryRecursive
import org.example.ssh.base.executeCmd
import org.example.ssh.base.parseLsOutput
import java.io.File

class PullLogFiles {
    // 远程日志目录
    var remoteLogDir = "/home/mydesk-data/logs/v1"
    // 本地日志目录
    var localLogDir = "./docker/logs/v1"
    var dateStr = "2025-01-12"

    fun deleteLogDir(ssh: SSHClient) {
        val sftp: SFTPClient = ssh.newSFTPClient()
        try {
            deleteDirectoryRecursive(sftp, remoteLogDir)
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            sftp.close()
        }
    }

    fun deleteLogFiles(ssh: SSHClient) {
        val res = executeCmd(ssh, "cd $remoteLogDir && ls -la")

        val remoteLogList = parseLsOutput(res).filter {
            !it.isDirectory && it.name.endsWith(".log") && it.name.contains(dateStr)
        }
        val sftp: SFTPClient = ssh.newSFTPClient()
        try {
            for (log in remoteLogList) {
                sftp.rm("$remoteLogDir/${log.name}")
                println("文件: $remoteLogDir/${log.name} 删除成功")
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            sftp.close()
        }
    }

    /**
     * 同步远程日志文件 到 本地日志目录
     */
    fun pullLogFiles(ssh: SSHClient) {
        val dir = File(localLogDir)
        if (!dir.exists()) {
            dir.mkdirs()
        }
        val res = executeCmd(ssh, "cd $remoteLogDir && ls -la")

        val remoteLogList = parseLsOutput(res).filter {
            !it.isDirectory && it.name.endsWith(".log") && it.name.contains(dateStr)
        }
        val localLogs = dir.listFiles()!!.filter {
            it.isFile && !it.name.endsWith(".log") && it.name.contains(dateStr)
        }

        // 需要同步的文件
        val needDownLogs = mutableListOf<String>()
        for (remoteLog in remoteLogList) {
            val localLog = localLogs.find {
                it.name == remoteLog.name
            }
            val kb1 = 1024 * 1024
            // 超过 +- 1kb，或者本地文件不存在的
            if (localLog == null ||
                localLog.length() < remoteLog.size - kb1 ||
                localLog.length() > remoteLog.size + kb1
            ) {
                needDownLogs.add(remoteLog.name)
            }
        }

        val sftp: SFTPClient = ssh.newSFTPClient()
        try {
            // 开始同步文件
            for (logName in needDownLogs) {
                sftp.get("$remoteLogDir/${logName}", "${localLogDir}/${logName}")
                println("文件: $remoteLogDir/${logName} 下载成功")
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            sftp.close()
        }

    }
}